package com.eightbears.beboy.ui.user.fragment;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.eightbears.beboy.R;
import com.eightbears.beboy.adapter.MyProfitAdapter;
import com.eightbears.beboy.base.BaseFragment;
import com.eightbears.beboy.base.util.CommonAPI;
import com.eightbears.beboy.base.util.ErrorUtils;
import com.eightbears.beboy.base.util.GsonUtil;
import com.eightbears.beboy.base.util.SPUtil;
import com.eightbears.beboy.base.util.okhttp.OkHttpUtils;
import com.eightbears.beboy.base.util.okhttp.callback.StringCallback;
import com.eightbears.beboy.base.view.layout.MyGridLayoutManager;
import com.eightbears.beboy.base.view.layout.MyLinearLayoutManager;
import com.eightbears.beboy.entity.ProfitEntity;
import com.eightbears.beboy.entity.UserInfoEntity;
import com.eightbears.beboy.entity.status.Status_Error;
import com.eightbears.beboy.ui.user.activity.DrawMoneyActivity;
import com.eightbears.beboy.ui.user.activity.MyProfitActivity;
import com.socks.library.KLog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;

import static com.eightbears.beboy.base.util.CommonAPI.CONNECTION_STATUS_SUCCESS;
import static com.eightbears.beboy.base.util.CommonAPI.KEY_HTTP_HEADER;
import static com.eightbears.beboy.base.util.CommonAPI.URL_MLM_PROFIT;
import static com.eightbears.beboy.base.util.CommonAPI.delayMillis;
import static com.eightbears.beboy.ui.user.activity.PaymentActivity.EVENT_MY_PAY;
import static com.eightbears.beboy.ui.user.activity.SettingActivity.EVENT_USER_HEAD_UPDATE;
import static com.eightbears.beboy.ui.user.activity.SystemMessageActivity.PARAMS_IS_SYSTEM_MESSAGE;
import static com.eightbears.beboy.ui.user.fragment.MyFragment.EVENT_UPDATE_USERINFO;

/**
 * 利润流水
 */
public class RrofitFragment extends BaseFragment implements
        SwipeRefreshLayout.OnRefreshListener {
    public static final String PARAMS_MY_CLIENT = "clientType";
    public static final String WITHDRAW_MLM="mlm";
    public static final String PROFIT_INFO = "profit";
    @BindView(R.id.rv_list)
    RecyclerView mRvList;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout mSwipeLayout;
    @BindView(R.id.ll_list)
    LinearLayout mLlList;

    private int page = 1;
    private boolean isErr = true;
    private int isEnd = 0;

    private String clientParam;
    private TextView mTv_tol_add;
    private TextView mTv_take_profit;
    private TextView mTv_accumulate_num;
    private MyProfitAdapter mMyProfitAdapter;
    private LinearLayout mLl_all_profit;
    private UserInfoEntity mUserInfoEntity;
    private ProfitEntity mProfitEntity;
    private String mRemain_balance;
    private String[] mKey;
    private Object[] mParam;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_my_profit, container, false);
        ButterKnife.bind(this, view);
        EventBus.getDefault().register(this);
        initView();
        initData();
        initEvent();
        return view;
    }

    @Override
    protected void initView() {
        mUserInfoEntity = (UserInfoEntity)getActivity().getIntent().getExtras().get(EVENT_UPDATE_USERINFO);



        mSwipeLayout.setRefreshing(true);
        mSwipeLayout.setOnRefreshListener(this);
//        CommonUtils.loadImageView(getActivity(), mUserEntity.getData().getCover(), R.mipmap.default_head, iv_user_head);
        mSwipeLayout.setProgressViewOffset(true, 0, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 100, getResources().getDisplayMetrics()));
        mSwipeLayout.setColorSchemeColors(getResources().getColor(R.color.text_select_color),
                getResources().getColor(R.color.text_select_color),
                getResources().getColor(R.color.text_select_color),
                getResources().getColor(R.color.text_select_color));
        MyLinearLayoutManager mWrapHeightGridLayoutManager = new MyLinearLayoutManager(getActivity());
        mRvList.setLayoutManager(mWrapHeightGridLayoutManager);
        mMyProfitAdapter = new MyProfitAdapter();
        mMyProfitAdapter.addHeaderView(addHeader());                //添加头部布局
        mMyProfitAdapter.addFooterView(addFooter());           //添加头部布局
        mMyProfitAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);//添加加载动画
        mRvList.setAdapter(mMyProfitAdapter);
    }

    @Override
    protected void initData() {
        getData();
    }

    @Override
    protected void initEvent() {
//        orderListAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
//            @Override
//            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
//                orderInfo = (OrderEntity.OrderInfo) adapter.getData().get(position);
//                switch (view.getId()) {
//                    case R.id.shop_info_meal:
//                        startLocalActivity(OrderDetailActivity.class, PARAMS_ORDER_LIST, orderInfo);
//                        break;
//                    case R.id.tv_shopbook_mealbug:
//                        if (builder == null) {
//                            String code = "beboy://code/" + orderInfo.getCode();
//                            builder = new CodeDialog.Builder(getActivity());
//                            builder.setBitmap(CodeUtils.createImage(code, 150, 150, null));
//                            builder.setTitle(orderInfo.getCoupon().getTitle());
//                            builder.setTv_price("￥" + orderInfo.getCoupon().getPrice());
//                            builder.setTv_code(orderInfo.getCode() + "");
//                        }
//                        builder.create().show();
//                        break;
//                }
//            }
//        });
    }



    private void getData() {
        OkHttpUtils.get().url(URL_MLM_PROFIT)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .build().execute(new StringCallback() {
            @Override
            public void onResponse(String response) {
                KLog.e(response);
                mSwipeLayout.setRefreshing(false);
                mProfitEntity = GsonUtil.fromJson(response, ProfitEntity.class);
                ProfitEntity.DataBean.LogsBean logs = mProfitEntity.getData().getLogs();
                if (CONNECTION_STATUS_SUCCESS.equals(String.valueOf(mProfitEntity.getStatus_code()))) {
                    if (mProfitEntity.getData().getLogs().getList().size() == 3)
                        mLl_all_profit.setVisibility(View.VISIBLE);
                    isEnd = mProfitEntity.getData().getLogs().getIs_end();
                    mMyProfitAdapter.setNewData(mProfitEntity.getData().getLogs().getList());
                    mTv_tol_add.setText(mProfitEntity.getData().getToday_balance());
                    mRemain_balance = mProfitEntity.getData().getRemain_balance();
                    mTv_take_profit.setText(mRemain_balance);
                    mTv_accumulate_num.setText("￥" + mProfitEntity.getData().getTotal_balance());
                    mKey = new String[]{ EVENT_UPDATE_USERINFO, CommonAPI.WITHDRAW,PROFIT_INFO};
                    mParam = new Object[]{mUserInfoEntity, WITHDRAW_MLM, mRemain_balance};
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                mSwipeLayout.setRefreshing(false);
                isErr = false;
                KLog.e(e.getMessage());
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(getActivity(), status_error);
            }
        });
    }

    /**
     * 添加recyclerView头部推荐布局
     *
     * @return
     */
    private View addHeader() {

        View view = getActivity().getLayoutInflater().inflate(R.layout.head_client_profit, null);
        mTv_tol_add = (TextView) view.findViewById(R.id.tv_tol_add);
        mTv_take_profit = (TextView) view.findViewById(R.id.tv_take_profit);
        mTv_accumulate_num = (TextView) view.findViewById(R.id.tv_accumulate_num);
        Button btn_take_profit = (Button) view.findViewById(R.id.btn_take_profit);
        btn_take_profit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startLocalActivity(DrawMoneyActivity.class, mKey,mParam);
            }
        });
        return view;
    }
    /**
     * 添加Adapter底部
     * @return
     */
    private View addFooter() {
        View view = getActivity().getLayoutInflater().inflate(R.layout.view_foot_profit, null);
        mLl_all_profit = (LinearLayout) view.findViewById(R.id.ll_all_profit);
        mLl_all_profit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startLocalActivity(MyProfitActivity.class);
            }
        });
        return view;
    }

    @Override
    public void onRefresh() {
        mMyProfitAdapter.setEnableLoadMore(false);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                isErr = true;
                page = 1;
                mMyProfitAdapter.getData().clear();
                initData();
                mMyProfitAdapter.setEnableLoadMore(true);
            }
        }, delayMillis);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDataSynEvent(String event) {
        switch (event) {
            case EVENT_MY_PAY:
                initView();
                initData();
                break;
        }
    }
}
